//
//  NYPlaceholderTextView.m
//  BS
//
//  Created by neal on 15/8/21.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYPlaceholderTextView.h"

@interface NYPlaceholderTextView ()
/* placeholderlabel */
@property(nonatomic , weak) UILabel *placeholderlabel;

@end
@implementation NYPlaceholderTextView
- (UILabel *)placeholderlabel
{
    if (_placeholderlabel == nil) {
        UILabel *label = [[UILabel alloc]init];
        label.x = 4;
        label.y = 8;
        label.numberOfLines = 0;
        [self addSubview:label];
        _placeholderlabel = label;
    }
    return _placeholderlabel;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.font = [UIFont systemFontOfSize:15];
        
        self.placeholderColor = [UIColor grayColor];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}
- (void)textDidChange
{
    self.placeholderlabel.hidden = self.hasText;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.placeholderlabel.width = self.width - 2*self.placeholderlabel.x;
    [self.placeholderlabel sizeToFit];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
- (void)drawRect:(CGRect)rect{
    if (self.hasText) {
        return;
    }
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
    
    CGFloat x = 4;
    CGFloat y = 8;
    CGRect placeholerrect = CGRectMake(x, y, self.width - 2*x, self.height);
    [self.placeholder drawInRect:placeholerrect withAttributes:attrs];
}
*/
- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    self.placeholderlabel.text = placeholder;
    [self setNeedsLayout];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    self.placeholderlabel.textColor = placeholderColor;
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    self.placeholderlabel.hidden = self.hasText;
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    self.placeholderlabel.hidden = self.hasText;
}
- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.placeholderlabel.font = font;
    [self setNeedsLayout];
}
@end
